<?php

namespace app\result;

class ToolsResult extends BaseResult
{
    // 加密函数
    public static function encrypt($data, $key, $iv)
    {
        $encrypted = openssl_encrypt($data, "AES-128-CBC", $key, 0, $iv);
        return base64_encode($encrypted);
    }

    // 解密函数
    public static function decrypt($data, $key, $iv)
    {
        $decrypted = openssl_decrypt(base64_decode($data), "AES-256-CBC", $key, OPENSSL_RAW_DATA, base64_decode($iv));
        return $decrypted;
    }

    // 返回加密数据
    public static function encode_data($data)
    {
        $key = '您的密钥'; // 与前端相同的密钥
        $iv = '您的初始化向量'; // 与前端相同的IV
        $encryptedData = self:: encrypt(json_encode($data), $key, $iv);
        echo $encryptedData;
    }

    public static function ip_to_region($ip)
    {
        $ckey = 'ip2region'.$ip;
        if ($data = cache($ckey)){
            return $data;
        }
        $key = config('tools.ip_key');
        //高德地图
        $url = "http://restapi.amap.com/v3/ip?ip={$ip}&output=json&key=$key";
        $result = json_decode(file_get_contents($url), true);
        if ($result['status'] == '1') {
            $arr['country'] = $result['country'] ?? '中国';
            $arr['province'] = $result['province'] ?: '未知';
            $arr['city'] = $result['city'] ?: '未知';
            cache($ckey, $arr, 86400);
            return $arr;
        }
        return ['country' => '未知', 'province' => '未知', 'city' => '未知'];
    }

    //使用ip2region查询
    public static function ip2region($ip)
    {
        if (!class_exists('\Ip2Region')) {
            return ['country' => '未知', 'province' => '未知', 'city' => '未知'];
        }
        $ip2region = new \Ip2Region();
        try {
            $geo = $ip2region->memorySearch($ip);
        } catch (\Exception $e) {
            bs_log($e->getMessage(), 'error', 'ip2regionv.log');
            return ['country' => '未知', 'province' => '未知', 'city' => '未知'];
        }
        $arr = [];
        if (stripos($geo['region'], '中国') === 0 && stripos($geo['region'], '内网') === false) {
            $region = array_values(array_filter(explode('|', $geo['region'])));//中国 广东 广州 电信
            if (empty($region[2])) {
                $arr = self::ip_to_region($ip);
            } else {
                $region[0] = $region[0] ?? '未知';
                $region[1] = $region[1] ?? '未知';
                $region[2] = $region[2] ?? '未知';
                [$arr['country'], $arr['province'], $arr['city']] = $region;
                empty($region['2']) && bs_log($region, 'ip2region', 'ip2regionv.log');
            }
        }

        return $arr;
    }

    /** 文件大小格式化
     * @param $size        int
     * @param $delimiter
     * @return string
     */
    public static function format_bytes($size, $delimiter = '')
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}
